Day 25~Day 28,我們已經一路學過:
LLM / Token / Context Window / Inference
Embedding / Vector Database
RAG
AI Agent
Tool Calling
Memory
Workflow
Guardrail
Human Approval
Task Queue
Worker Pool
Durable Execution
Tool Gateway
OAuth
Sandbox
Multi-Tenant
所以 Day 29 不會重新長篇解釋這些已經詳細介紹過的概念。
今天要把前面的 Building Blocks 組起來,回答一個更接近真正 Startup /
Enterprise Product 的 System Design 題目:
如果今天要把 RAG + AI Agent 做成一個可以賣給很多公司的 AI
SaaS,要怎麼設計?
例如我們做一個 AI Assistant Platform:
Company A
→ 上傳自己的 Documents
→ 建立自己的 RAG Knowledge Base
→ 讓自己的 Employees 使用 AI Agent
Company B
→ 也使用同一個 Product
→ 但 Company B 絕對不能看到 Company A 的 Data
這時問題就不只是:
How does RAG work?
How does Agent call tools?
而是:
How do we separate customers?
How do we manage organizations and users?
How do we enforce plans and quotas?
How do we measure usage?
How do we bill customers?
How do enterprise users log in?
How do we isolate data?
How do we manage encryption keys?
How do we prevent one customer from slowing everyone else down?
How do we calculate each customer's AI cost?
這就是今天的:
AI SaaS System Design
逐字拆開:
S = Software = 軟體
a = as = 作為
a = a = 一個
S = Service = 服務
完整:
Software as a Service
= 軟體即服務
簡單理解:
User 不需要自己購買、安裝、維護整套 Software Infrastructure,而是透過
Internet 使用 Provider 提供的 Software Service。
例如:
Traditional Software
Buy software
↓
Install on computer/server
↓
Maintain yourself
SaaS:
Open Browser
↓
Login
↓
Use Service
AI SaaS
就是:
以 SaaS 方式提供 AI Capability 的 Product。
例如:
AI Customer Support
AI Research Assistant
AI Coding Assistant
AI Document Search
AI Meeting Assistant
AI Agent Platform
今天假設我們設計:
Enterprise AI Assistant SaaS
每家公司可以:
Create Workspace
Invite Employees
Upload Documents
Build RAG Knowledge Base
Connect Tools
Run AI Agents
Track Usage
Pay Subscription
Customer(客戶)
付費購買 Product / Service 的個人或 Organization。
在 B2B SaaS 中,一個 Customer 通常可能是一家公司。
逐字:
B = Business = 企業 / 商業
2 / to = 對
B = Business = 企業 / 商業
完整:
Business-to-Business
= 企業對企業
意思:
一家公司把 Product / Service 賣給另一家公司。
例如:
Our AI SaaS
↓
TSMC
Microsoft
Startup A
Company B
逐字:
B = Business = 企業
2 / to = 對
C = Consumer = 消費者
中文:
企業對消費者
例如:
Company
↓
Individual User
今天主要討論:
B2B AI SaaS
Tenant 之前已經接觸過,這裡直接套用。
在 SaaS 中:
一個 Tenant 通常代表一個邏輯上獨立的 Customer / Organization。
例如:
tenant_001 = Company A
tenant_002 = Company B
tenant_003 = Company C
Multi-Tenant 已經學過。
核心:
One SaaS Platform
↓
Many Customers
但每個 Tenant 必須:
Data isolated
Permissions isolated
Usage tracked separately
Billing calculated separately
Quotas enforced separately
Organization(組織)
SaaS 中代表一家公司、團隊或正式組織的 Object。
例如:
Organization:
TSMC
Users:
Alvin
Alice
Bob
一個 Organization 通常會對應:
tenant_id
但實際 Product Model 不一定完全相同。
Workspace(工作空間)
Organization 裡用來分隔 Projects、Teams、Resources 或 Collaboration
Context 的邏輯空間。
例如:
Organization: TSMC
Workspace 1:
IT Department
Workspace 2:
Manufacturing
Workspace 3:
HR
簡單理解:
Organization
→ Company level
Workspace
→ Team / Project level
例如:
Organization
TSMC
│
├── Workspace: IT
├── Workspace: HR
└── Workspace: Fab Operations
Membership(成員關係)
描述某個 User 是否屬於某個 Organization / Workspace,以及他的 Role。
例如:
user_id = user_123
organization_id = org_456
role = ADMIN
這就是一筆 Membership。
Role 已經學過。
SaaS 中常見:
OWNER
ADMIN
MEMBER
VIEWER
逐字:
R = Role = 角色
B = Based = 基於
A = Access = 存取
C = Control = 控制
完整:
Role-Based Access Control
= 基於角色的存取控制
RBAC 的核心:
不直接為每一個 User 個別設定所有 Permissions,而是先定義 Role,再把
Permissions 給 Role。
例如:
OWNER
→ manage billing
→ delete organization
→ invite users
ADMIN
→ invite users
→ manage workspace
MEMBER
→ use AI
→ upload documents
VIEWER
→ read only
然後:
Alvin → ADMIN
Bob → MEMBER
Permission 之前已經學過。
RBAC 可以理解:
User
↓
Role
↓
Permissions
而不是:
User
↓
Hundreds of individual rules
Entitlement(權益 / 可使用功能權限)
這是 SaaS 很重要的新名詞。
Entitlement 描述某個 Customer 因為 Subscription Plan
而「有資格使用哪些 Product Features」。
例如:
Free Plan
→ 1 workspace
→ 100 AI queries/month
→ no SSO
Pro Plan
→ 10 workspaces
→ 10,000 AI queries/month
→ advanced models
Enterprise Plan
→ unlimited workspaces
→ SSO
→ audit logs
→ custom retention
這些:
Can use SSO?
Can create 20 workspaces?
Can access GPT-X?
就是 Entitlements。
非常容易混淆。
回答:
Who can do this inside the organization?
例如:
Can Alvin delete this workspace?
回答:
Did this customer purchase access to this feature?
例如:
Does Company A's plan include SSO?
所以:
RBAC
→ User permission
Entitlement
→ Product / Plan permission
Subscription(訂閱)
Customer 按某種週期持續付費使用 Product / Service。
例如:
Monthly Subscription
Annual Subscription
Plan(方案)
Subscription Plan(訂閱方案)
例如:
Free
Pro
Business
Enterprise
不同 Plan 可以有不同:
Price
Quota
Features
Entitlements
Support
Security Features
Billing(計費 / 帳務)
計算 Customer 應付多少 Money,並產生相關帳務資訊的 Process。
Billing 不等於 Payment。
How much should the customer pay?
Did we actually collect the money?
例如:
Usage
↓
Billing
↓
Invoice = $500
↓
Payment Provider
↓
Customer pays $500
Invoice(發票 / 帳單)
正式列出 Customer 應支付金額與明細的 Document / Record。
例如:
Base subscription: $200
AI usage: $250
Storage: $50
Total: $500
Usage-Based Billing(依使用量計費)
Customer 的費用根據實際使用量計算。
例如:
1M LLM tokens
500 Agent tasks
100 GB storage
10,000 API calls
Meter(計量器)
日常:
Electricity meter
→ 電表
Software SaaS:
用來定義「我們要計算哪一種 Usage」的邏輯單位。
例如:
Meter:
LLM_INPUT_TOKENS
Meter:
LLM_OUTPUT_TOKENS
Meter:
AGENT_TASK
Meter:
STORAGE_GB
Metering(使用量計量)
收集並計算 Customer 使用了多少 Billable Resource。
例如:
Tenant A
↓
LLM request
↓
Input tokens = 2,000
Output tokens = 500
↓
Usage Event
↓
Metering System
Billable(可計費的)
會被納入 Customer 費用計算的 Usage。
不是所有 Internal Events 都一定 Billable。
例如:
Internal health check
通常不應算 Customer Usage。
Event 已學過。
Usage Event(使用量事件)
描述某個 Tenant 發生了一筆可計量 Usage。
例如:
{
"tenant_id": "tenant_A",
"meter": "LLM_INPUT_TOKENS",
"quantity": 2000
}
Usage Tracking(使用量追蹤)
持續記錄 Customer 使用 Product 的情況。
可以用於:
Billing
Quota
Analytics
Cost Attribution
Abuse Detection
Capacity Planning
Quota Day 28 已經解釋過,所以這裡直接套用。
例如:
Free Plan:
100 Agent Tasks / month
如果 User 已使用:
100
下一次 Request:
Quota exceeded
Soft Limit(軟限制)
超過 Limit 時,不一定立即 Block,而是 Warning 或允許暫時超量。
例如:
80% usage
→ warning
100%
→ still allow
120%
→ block
Hard Limit(硬限制)
一旦超過就直接禁止繼續使用。
例如:
Storage quota = 100 GB
Current = 100 GB
Upload
→ DENY
Overage(超額使用)
Customer 使用量超過 Plan 原本包含的額度。
例如:
Plan includes:
1M tokens
Actual:
1.5M tokens
Overage:
0.5M tokens
可以:
Charge extra
或:
Block
取決於 Product Policy。
Attribution(歸屬 / 歸因)
Cost Attribution(成本歸屬)
找出某筆 Infrastructure / AI Cost 應該算到哪個
Tenant、Workspace、Feature 或 Task。
例如:
LLM cost = $0.08
要知道:
Tenant = Company A
Workspace = Research
Agent Task = task_123
Chargeback(成本回收 / 內部計費)
在 Cloud / Enterprise Cost Management Context:
根據實際 Resource Usage,把成本正式分攤或收取到不同 Department /
Customer。
例如:
HR used $500
Engineering used $2,000
公司可能真的把這些 Cost 計入各 Department Budget。
Showback(成本展示)
告訴 Team:「你用了多少、如果計費會是多少」,但不一定真的向該 Team
收費。
例如 Dashboard:
Engineering AI Usage
Estimated Cost: $2,000
但不真的扣 Department Budget。
Chargeback
→ actually allocate / charge cost
Showback
→ show cost visibility
Provisioning
Provision → 提供 / 配置
Provisioning → 建立並配置所需資源
Tenant Provisioning(租戶佈建)
新 Customer 加入 SaaS 時,自動建立它需要的 Resources。
例如:
Create tenant record
↓
Create default workspace
↓
Create admin membership
↓
Initialize quotas
↓
Create storage namespace
↓
Create encryption configuration
↓
Enable plan entitlements
Onboarding(導入 / 新手啟用流程)
新 User / Customer 第一次開始使用 Product 的 Process。
例如:
Create Organization
↓
Invite Team
↓
Connect Google Drive
↓
Upload Documents
↓
Create First Agent
Provisioning 偏:
System resource setup
Onboarding 偏:
Customer getting started
Offboarding(退出 / 離場流程)
Customer / User 離開 Service 時的處理流程。
例如:
Disable account
Revoke credentials
Export data
Delete data
End subscription
Enterprise SaaS 一定要考慮:
What happens when customer leaves?
Retention 之前已接觸。
Data Retention Policy(資料保留政策)
Data 要保存多久,以及什麼時候 Delete。
例如:
Chat history:
30 days
Audit logs:
1 year
Deleted tenant:
purge after 30 days
Purge(徹底清除)
從 System 中永久清除 Data。
和:
Soft Delete
不同。
Soft Delete(軟刪除)
Data 還存在 Database,但標記為 Deleted。
例如:
deleted_at = 2026-10-13
Normal Query 不再顯示。
Hard Delete(硬刪除)
真正從 Storage 中移除 Data。
例如:
DELETE FROM users WHERE id = ...
實際 Enterprise System 還要考慮:
Backups
Replicas
Object Storage
Vector Index
Logs
是否也需要清除。
Tenant-Aware(具租戶意識的)
Component 知道每個 Request / Data 屬於哪個 Tenant。
例如:
tenant_id = tenant_A
必須一路傳:
API
↓
Service
↓
Database Query
↓
Cache
↓
RAG Retrieval
↓
Usage Metering
Tenant Context(租戶上下文)
Current Request 中用來表示「現在代表哪個 Tenant 執行」的 Context。
例如:
user_id = Alvin
tenant_id = TSMC
workspace_id = IT
錯誤:
SELECT * FROM documents
WHERE document_id = 123;
如果 document_id 猜得到,可能讀到別人的 Data。
更安全的邏輯:
SELECT * FROM documents
WHERE tenant_id = ?
AND document_id = ?;
也就是:
每次 Data Access 都必須考慮 Tenant Boundary。
Shared Database(共用資料庫)
多個 Tenants 使用同一個 Database。
例如:
One PostgreSQL Database
documents
----------------
tenant_id
document_id
content
優點:
Simple operations
Lower cost
Easy onboarding
缺點:
Isolation depends heavily on application/database rules
Large tenant may affect others
Harder per-tenant backup/restore
Schema 已學過。
Shared Schema(共用 Schema)
Tenants 共用相同 Tables,透過
tenant_id區分 Data。
例如:
users
documents
agents
所有 Customers 都在同樣 Tables。
Separate Schema(獨立 Schema)
每個 Tenant 在同一 Database Server 中使用不同 Database Schema。
例如:
tenant_a.documents
tenant_b.documents
tenant_c.documents
Isolation 比 Shared Schema 更強一些,但 Tenant 數量很大時:
Schema management
Migration
Operations
會更複雜。
Separate Database(獨立資料庫)
每個 Tenant 有自己的 Database。
Company A
→ DB A
Company B
→ DB B
優點:
Strong isolation
Independent backup
Independent scaling
缺點:
Higher cost
More operational complexity
Migration management
Connection management
可以整理:
Strategy Isolation Cost Operational Complexity
Shared DB + Shared Schema 較低 較低 較低
Shared DB + Separate Schema 中 中 中
Separate Database 高 高 高
沒有永遠最好的答案。
要看:
Number of tenants
Enterprise requirements
Compliance
Cost
Scale
Operational capability
Hybrid(混合式)
Hybrid Isolation(混合隔離)
例如:
Small customers
→ Shared Database
Large Enterprise Customer
→ Dedicated Database
這是很常見的 Trade-off 思路。
Dedicated(專用的)
某個 Resource 只給特定 Customer 使用。
例如:
Dedicated Database
Dedicated Vector Index
Dedicated Worker Pool
Shared Infrastructure(共用基礎設施)
多個 Tenants 共用 Servers、Databases、Workers 或其他 Resources。
優點:
Better utilization
Lower cost
但要處理:
Isolation
Noisy Neighbor
Fairness
Security
Data Isolation 之前已經接觸。
AI SaaS 特別要注意:
Relational DB
Object Storage
Vector Database
Cache
Search Index
Logs
Agent Memory
Tool Credentials
全部都要有 Tenant Boundary。
Day 26 已經學過 Vector Database。
錯誤 Retrieval:
Search all vectors
↓
Return closest result
可能:
Company A query
↓
Company B document
嚴重 Data Leak。
應該:
Query
↓
tenant_id filter
↓
workspace filter
↓
ACL filter
↓
Vector Search
Namespace(命名空間)
把 Resources 放進不同 Logical Space,避免不同 Groups 的 Names / Data
混在一起。
例如 Vector Store:
namespace = tenant_A
namespace = tenant_B
簡單理解:
像不同 Customer 各有自己的抽屜。
Tenant-Specific(租戶專屬)
每個 Tenant 使用不同 Namespace。
例如:
Vector Index
├── namespace: company_A
├── namespace: company_B
└── namespace: company_C
Cache 已學過。
錯誤:
cache key = user_profile_123
如果不同 Tenants 都可能有:
user_id = 123
就有 Collision Risk。
更合理:
tenant_A:user_profile:123
tenant_B:user_profile:123
Composite(組合的)
Composite Key(複合鍵)
使用多個 Fields 一起形成唯一 Key。
例如:
tenant_id + user_id
而不是只用:
user_id
逐字:
S = Single = 單一
S = Sign = 登入 / 簽入
O = On = 啟用 / 登入狀態
完整:
Single Sign-On
= 單一登入
User 登入一次 Identity Provider 後,可以存取多個
Applications,而不用每個 Application 都重新輸入一組帳號密碼。
例如 Company Employee:
Login Company Identity System
↓
Gmail
Slack
Internal Dashboard
Our AI SaaS
不用每個 Service 都建立不同 Password。
Identity Provider
簡稱常寫:
IdP
逐字:
Id = Identity = 身分
P = Provider = 提供者
完整:
Identity Provider
= 身分提供者
注意 Id 不是:
I = ...
d = ...
它是:
Identity
的常見縮寫形式。
IdP 負責:
Authenticate User
Manage Identity
Issue Authentication Information
Service Provider(服務提供者)
在 SSO Context:
User 想要使用的 Application。
例如:
Our AI SaaS
就是 Service Provider。
逐字:
S = Service = 服務
P = Provider = 提供者
中文:
服務提供者
逐字:
S = Security = 安全
A = Assertion = 聲明 / 斷言
M = Markup = 標記
L = Language = 語言
完整:
Security Assertion Markup Language
= 安全聲明標記語言
Assertion(聲明 / 斷言)
在 Authentication Context:
一個 System 對 User Identity / Authentication State 做出的可信聲明。
例如 IdP 告訴 SaaS:
This user is:
alvin@company.com
Authenticated:
true
Department:
Engineering
這些就是 Identity Assertions。
Markup Language(標記語言)
使用 Tags / Structured Markup 描述 Document Structure / Data。
例如:
HTML
XML
SAML Message 常以 XML Format 表達。
逐字:
X = Extensible = 可擴充的
M = Markup = 標記
L = Language = 語言
中文:
可擴充標記語言
它是一種 Structured Text Format。
Employee
↓
Our AI SaaS
↓
Redirect to Company IdP
↓
Employee logs in
↓
IdP creates SAML Assertion
↓
AI SaaS validates Assertion
↓
Create User Session
Enterprise Customer 可能說:
We don't want employees creating separate passwords.
Use our corporate identity system.
這時:
SAML SSO
就是常見 Enterprise Requirement。
逐字:
S = System = 系統
C = Cross-domain = 跨網域
I = Identity = 身分
M = Management = 管理
完整:
System for Cross-domain Identity Management
= 跨網域身分管理系統
簡單說:
讓 Company 的 Identity System 可以自動在 SaaS 中建立、更新、停用
Users。
沒有 SCIM:
Employee joins company
↓
Admin manually creates SaaS account
Employee leaves company
↓
Admin must remember to delete account
有 SCIM:
Company Identity System
↓
Automatically provision user
離職:
Identity System
↓
Automatically deactivate SaaS user
Tenant Provisioning 是建立 Customer Resources。
User Provisioning(使用者佈建)
建立並配置 User Account。
例如:
Create user
Assign organization
Assign group
Assign role
Deprovisioning(解除佈建 / 停用資源)
User 不再需要 Access 時,移除或停用其 Account / Permissions。
例如 Employee 離職:
SCIM
↓
Deactivate user
↓
Revoke access
非常重要。
回答:
How does the user log in?
回答:
How are user accounts created / updated / disabled?
所以:
SSO
→ Authentication experience
SCIM
→ Identity lifecycle management
逐字:
K = Key = 金鑰
M = Management = 管理
S = Service = 服務
完整:
Key Management Service
= 金鑰管理服務
Encryption 已學過。
Encryption Key(加密金鑰)
Encryption Algorithm 用來把 Plaintext 轉成
Ciphertext,或在適當條件下解密 Data 的 Key Material。
簡單理解:
Data
+
Encryption Key
↓
Encrypted Data
Key Material(金鑰材料)
實際構成 Cryptographic Key 的 Sensitive Bits / Data。
不應該:
Put into logs
Send to LLM
Hard-code in source code
如果每個 Developer 都:
Store encryption key in source code
非常危險。
KMS 可以集中:
Generate keys
Store keys securely
Control access
Rotate keys
Audit key usage
Per-Tenant Encryption(每租戶加密)
不同 Tenants 可以使用不同 Encryption Key / Key Hierarchy。
例如:
Company A
→ Key A
Company B
→ Key B
如果 Key A 發生問題:
Impact can be limited to Company A
Hierarchy(階層)
Key Hierarchy(金鑰階層)
不直接用一把 Key 管所有 Data,而是用多層 Keys 管理 Encryption。
常見概念:
Master Key
↓
Data Encryption Key
↓
Actual Data
逐字:
D = Data = 資料
E = Encryption = 加密
K = Key = 金鑰
完整:
Data Encryption Key
= 資料加密金鑰
真正用來加密 Data 的 Key。
逐字:
K = Key = 金鑰
E = Encryption = 加密
K = Key = 金鑰
完整:
Key Encryption Key
= 金鑰加密金鑰
它的用途:
用來保護另一把 Key。
例如:
KEK
↓ encrypts
DEK
↓ encrypts
Customer Data
Envelope
Envelope = 信封
Envelope Encryption(信封式加密)
簡化:
Customer Data
↓ encrypted by DEK
DEK
↓ encrypted by KEK
為什麼?
因為:
Large Data
通常不需要直接全部送進 KMS 處理。
而是:
KMS protects keys
Application uses DEK to encrypt data
逐字:
B = Bring = 帶來
Y = Your = 你的
O = Own = 自己的
K = Key = 金鑰
完整:
Bring Your Own Key
= 自帶金鑰
Enterprise Customer 可能要求:
不想完全使用 SaaS Provider 管理的 Encryption Key,希望使用 Customer
自己控制的 Key。
這就是:
BYOK
通常是較進階 Enterprise Security Requirement。
Control Plane
Control = 控制
Plane = 平面 / 層面
中文常稱:
控制平面
簡單理解:
管理「System 應該怎麼運作」的 Management Layer。
例如 AI SaaS:
Create tenant
Manage subscription
Configure agent
Configure policy
Manage users
Manage credentials
Set quotas
這些偏 Control Plane。
Data Plane
Data = 資料
Plane = 平面 / 層面
中文:
資料平面
簡單理解:
真正處理 Customer Runtime Traffic / Data 的 Execution Layer。
例如:
Run RAG Query
Execute Agent
Retrieve Documents
Call LLM
Call Tools
這些偏 Data Plane。
Control Plane
→ configure / manage
Data Plane
→ execute / serve traffic
例如:
Control Plane:
Set Agent max_steps = 10
Data Plane:
Actually run the Agent with max_steps = 10
好處:
Different scaling needs
Different security boundaries
Different availability requirements
Cleaner architecture
例如:
Agent Runtime Traffic
可能非常大。
但:
Subscription Settings
Traffic 小很多。
不一定要完全用相同 Infrastructure。
有些 Architecture 也會使用:
Management Plane(管理平面)
不同 Company 對 Control Plane / Management Plane 的定義可能不同。
面試不要硬背成:
所有公司一定完全相同
核心理解:
把管理 / 配置 Operations 與 Runtime Data Processing 分開。
Control Plane
Organization Service
Subscription Service
Billing Service
Entitlement Service
Identity Configuration
Tenant Provisioning
Agent Configuration
Policy Configuration
Data Plane
Agent API
RAG Service
Agent Workers
Model Gateway
Tool Gateway
Vector Search
Document Retrieval
Day 28 有 Model Router。
Model Gateway(模型閘道)
Application 呼叫不同 AI Models 的統一入口。
例如:
AI Application
↓
Model Gateway
├── Model Provider A
├── Model Provider B
└── Internal Model
可以統一:
Authentication
Model Routing
Rate Limiting
Usage Tracking
Cost Tracking
Fallback
Logging
Provider(供應商 / 服務提供者)
AI Context:
提供 Model / Infrastructure / API 的 External Vendor 或 Internal
Platform。
例如:
Model Provider
Email Provider
Cloud Provider
Abstraction(抽象化)
Provider Abstraction(供應商抽象層)
Upper Layer 不直接依賴某個 Provider 的特殊 Interface,而是透過統一
Interface。
例如:
generate_text()
背後可能:
Provider A
Provider B
Vendor(供應商)
Lock-In(被綁定)
Vendor Lock-In(供應商綁定)
System 太依賴某個 Provider 的特殊 Technology / API,導致未來很難切換。
Provider Abstraction 可以降低部分 Lock-In。
但:
過度抽象也會增加 Complexity。
Entitlement Service(權益服務)
集中判斷某個 Tenant 是否可以使用某 Feature。
例如:
can_use_sso(tenant_A)
→ true
can_use_advanced_agent(tenant_B)
→ false
Subscription Service(訂閱服務)
管理 Customer 目前使用哪個 Plan,以及 Subscription Status。
例如:
ACTIVE
TRIAL
PAST_DUE
CANCELLED
Trial(試用)
Customer 在正式付費前,可以在有限時間 / 功能下試用 Product。
例如:
14-day free trial
Past Due(逾期未付款)
Payment Deadline 已過,但 Customer 尚未完成付款。
SaaS 要決定:
Immediately disable?
Grace period?
Read-only?
Keep data?
Grace Period(寬限期)
Deadline 過後仍暫時允許 Customer 使用 Service 的一段時間。
例如:
Payment failed
↓
7-day grace period
↓
Then suspend
Suspend(暫停)
暫時停止 Account / Tenant 使用某些或全部 Service,但不一定刪除 Data。
AI Request
↓
Agent / RAG / Model
↓
Usage Event
↓
Usage Queue
↓
Metering Service
↓
Usage Database
↓
Billing Aggregation
↓
Invoice
Aggregation(聚合 / 彙總)
把很多細小 Records 合併成 Summary。
例如:
1,000 token usage events
↓
Aggregate
↓
Tenant A used 5,000,000 tokens this month
Billing Aggregation(計費彙總)
把 Raw Usage Events 按 Tenant、Meter、Time Period 等方式加總,供
Billing 使用。
Time Period(時間區間)
例如:
Hourly
Daily
Monthly
Billing Cycle
Billing Cycle(計費週期)
Customer 帳務重複計算的時間週期。
例如:
Monthly
每個月結算一次。
Usage Event 如果重複送:
Token usage = 10,000
兩次,Billing 可能:
Charge 20,000
所以 Usage Pipeline 也需要之前學過的:
Idempotency / Deduplication
每個 Usage Event 可以有:
usage_event_id
例如:
evt_123
Metering Service:
evt_123 already processed?
↓
Yes
↓
Ignore duplicate
Provider 自己付出的成本。
例如:
LLM Provider cost = $0.01
Customer 被收取的價格。
例如:
Customer price = $0.03
Margin(利潤率 / 毛利空間)
簡化:
Revenue - Cost
AI SaaS 如果:
Customer pays $100
AI infrastructure costs $95
Business 很難健康。
所以 AI System Design 不能完全忽略:
Cost Control
Unit Economics(單位經濟模型)
分析每一個基本 Business Unit 的 Revenue 與 Cost。
AI SaaS 可以看:
Revenue per tenant
Cost per tenant
Revenue per agent task
Cost per agent task
Revenue per 1M tokens
Cost per 1M tokens
Agent Task
↓
task_id
tenant_id
workspace_id
model
input_tokens
output_tokens
tool_calls
storage_usage
↓
Cost Service
↓
Tenant Cost Record
Cost Center(成本中心)
Company 內部用來歸類 Cost 的 Department / Team / Business Unit。
例如:
Engineering
HR
Sales
Enterprise SaaS 可能允許:
Workspace → Cost Center
方便 Showback / Chargeback。
Day 28 已詳細解釋。
AI SaaS 中可能是:
Tenant A
→ launches 100,000 agent tasks
↓
Worker Pool saturated
↓
Tenant B becomes slow
所以需要:
Per-Tenant Quota
Rate Limit
Concurrency Limit
Fair Scheduling
一種更強 Isolation:
Tenant A
→ Worker Pool A
Tenant B
→ Worker Pool B
優點:
Strong performance isolation
缺點:
Higher cost
Lower resource utilization
More operations
All tenants
↓
Shared Queue / Worker Pool
優點:
Better utilization
Lower cost
缺點:
Need fairness
Need quotas
Noisy neighbor risk
Tier(等級 / 層級)
SaaS 可以依 Plan 提供不同 Infrastructure Tier。
例如:
Free Tier
Pro Tier
Enterprise Tier
例如:
Enterprise Customer
↓
Dedicated Worker Pool
Dedicated Database
Dedicated Vector Index
Customer-specific KMS key
成本高,但 Isolation 更強。
Region(區域)
Cloud Context:
一個大型 Geographic Infrastructure Area。
Regional Deployment(區域部署)
例如:
US Region
EU Region
Asia Region
Residency(居留 / 所在地)
Data Residency(資料駐留)
Customer Data 必須存放在特定 Geographic Region 的 Requirement。
例如:
EU Customer Data
→ must stay in EU
Enterprise / Regulatory Requirement 常會出現。
Data Residency Policy
例如:
tenant_A
home_region = us-east
tenant_B
home_region = eu-west
所有:
Database
Object Storage
Vector Store
Backups
都需要考慮這個 Requirement。
Request
↓
Identify tenant
↓
tenant.home_region
↓
Route request to correct regional stack
Cross-Region(跨區域)
Operation / Data 在不同 Cloud Regions 之間移動。
如果有 Data Residency Requirement:
Cross-region replication
不能隨便開。
Enterprise Requirements(企業級需求)
常見:
SSO
SCIM
RBAC
Audit Logs
Data Retention
Data Residency
Encryption
BYOK
Custom Quotas
Dedicated Infrastructure
SLA
Support
Export / Deletion
SLA 之前已詳細解釋。
Enterprise Plan 可能承諾:
99.9% availability
Support response time
這些可能寫進 Contract。
Compliance(合規)
System / Company 遵守法律、產業規範、Contract 或 Security
Requirements。
例如:
Data handling requirements
Audit requirements
Retention requirements
Access control requirements
Security:
How do we protect the system?
Compliance:
Do we satisfy required rules / standards / contracts?
兩者有重疊,但不是完全相同。
Audit Export(稽核紀錄匯出)
Enterprise Customer 可能要求:
Export all audit events
給自己的:
Security Team
Compliance Team
逐字:
S = Security = 安全
I = Information = 資訊
E = Event = 事件
M = Management = 管理
完整:
Security Information and Event Management
= 安全資訊與事件管理
集中收集、分析 Security Logs / Events,協助 Security Team
發現異常與調查事件的 System。
AI SaaS 可以:
Audit Events
↓
Export
↓
Customer SIEM
Webhook 之前已學過,這裡直接套用。
Enterprise SaaS 可以透過 Webhook:
Agent completed
Usage threshold reached
Security event occurred
通知 Customer System。
假設:
100,000 Organizations
10M Users
50M AI Requests / day
5M Agent Tasks / day
需要:
Multi-Tenant Isolation
High Availability
Scalable RAG
Scalable Agent Workers
Usage Metering
Billing
SSO / SCIM
RBAC
Audit
Cost Control
Regional Deployment
Enterprise Security
數字只是 System Design Assumption,不代表任何特定 Product 真實數字。
今天不重複 Functional Requirement 定義。
AI SaaS 需要:
Create Organization
Invite Users
Create Workspace
Upload Documents
Configure RAG
Create Agents
Connect Tools
Run Agent Tasks
View Usage
Manage Subscription
Configure SSO
Export Audit Logs
High Availability
Low Latency
Tenant Isolation
Security
Durability
Scalability
Auditability
Cost Efficiency
Data Residency
可以先有:
Tenant
Organization
Workspace
User
Membership
Subscription
Entitlement
Agent
KnowledgeBase
Document
CredentialReference
Task
UsageEvent
Invoice
AuditEvent
tenant
------
tenant_id
name
plan_id
home_region
status
created_at
membership
----------
tenant_id
user_id
role
status
created_at
subscription
------------
tenant_id
plan_id
status
billing_cycle
started_at
renew_at
entitlement
-----------
plan_id
feature
limit
例如:
PRO
advanced_agent
true
PRO
monthly_agent_tasks
10000
usage_event
-----------
event_id
tenant_id
workspace_id
task_id
meter
quantity
timestamp
audit_event
-----------
event_id
tenant_id
user_id
action
resource
result
timestamp
User:
Ask AI question
Flow:
User
↓
API Gateway
↓
Authentication
↓
Resolve Tenant Context
↓
Check Membership / RBAC
↓
Check Entitlement
↓
Check Quota
↓
AI Service
↓
RAG / Agent
↓
Model Gateway
↓
Response
↓
Emit Usage Event
↓
Metering
User
↓
Authentication
↓
Tenant Context
↓
RBAC
↓
Entitlement
↓
Quota
↓
Agent Service
↓
Task Queue
↓
Tenant-Aware Worker
↓
RAG / Tools / Model
↓
Task Result
↓
Usage Events
↓
Cost Attribution
↓
Billing
Question
↓
tenant_id
workspace_id
user permissions
↓
Embedding
↓
Vector Search
WHERE:
tenant_id = current tenant
workspace_id = allowed workspace
ACL = user allowed
↓
Relevant Chunks
↓
LLM
↓
Answer
最重要:
Tenant Filter 不是 UI Feature,而是 Security Boundary。
Agent
↓
Tool Gateway
↓
tenant_id
user_id
credential_reference
↓
Authorization
↓
Load correct tenant/user credential
↓
External Tool
絕不能:
Randomly reuse another tenant's token
Credential Reference(憑證參照)
Application State 不直接保存 Secret Value,而是保存指向 Secret Store
中 Credential 的 Reference。
例如:
credential_ref = cred_abc123
真正 Token:
Secret Manager
Customer selects Pro
↓
Subscription Service
↓
Payment / Billing Provider
↓
Payment confirmed
↓
Subscription = ACTIVE
↓
Entitlements updated
Upgrade(升級)
例如:
Free
↓
Pro
System 要更新:
Subscription
Entitlements
Quota
Billing
Downgrade(降級)
例如:
Enterprise
↓
Pro
問題可能更複雜。
如果 Enterprise 有:
100 workspaces
但 Pro 只允許:
10
不能隨便直接 Delete 90 個 Workspaces。
需要 Product Policy:
Prevent downgrade
Read-only excess resources
Grace period
Ask customer to reduce usage
每次使用 Feature 前:
Can tenant use this feature?
例如:
SSO Login
↓
Entitlement Service
↓
enterprise_sso = true?
Entitlement 不一定每次都查 Database。
可以:
Entitlement Service
↓
Cache
但 Plan Upgrade 後要考慮:
Cache invalidation
避免 User 已升級卻還被舊 Cache Block。
Agent Task
↓
Model Gateway
↓
Model returns token usage
↓
Usage Event
↓
Message Queue
↓
Metering Service
↓
Deduplicate
↓
Aggregate
↓
Usage Database
如果每個 AI Request 都:
Generate answer
↓
Wait for billing database
↓
Wait for aggregation
↓
Then respond
會增加 User Latency。
所以可以:
Critical Path:
Generate response
Async:
Usage processing
Billing aggregation
Analytics
但 Usage Event 必須可靠,否則:
Revenue leakage
Revenue(營收)
Leakage(流失 / 漏掉)
Revenue Leakage(營收流失)
Customer 實際使用了 Service,但因為 Metering / Billing Error
沒有正確計費。
例如:
1M tokens used
↓
Usage event lost
↓
Customer charged for 0
Billing Correctness(計費正確性)
Customer 被計算的 Usage / Price 應正確、可追查,而且不能因 Duplicate
Event 重複收費。
需要:
Durable usage events
Idempotency
Deduplication
Auditability
Reconciliation
Reconciliation Day 28 已學過。
例如:
Model Gateway logs
vs
Usage Metering DB
每天比較:
Did we miss usage events?
Did we double-count?
例如:
Tenant A monthly AI budget
= $10,000
到:
80%
→ alert
100%
→ policy decision:
throttle / block / require approval
不同 Plan:
Free
→ small model
Pro
→ standard model
Enterprise
→ advanced model
Model Router 先查:
Entitlement
再選 Model。
某些 Enterprise Customer 可能要求:
Dedicated Model Endpoint
意思:
特定 Model Serving Resource 專門提供給該 Customer。
優點:
Isolation
Predictable capacity
缺點:
Cost
Operations
Lower utilization
Reservation(預留)
Capacity Reservation(容量預留)
預先保留一定 Compute Capacity 給特定 Customer。
例如:
Enterprise Tenant A
→ reserve 100 concurrent agent slots
Burst(突發)
Burst Capacity(突發容量)
短時間允許使用超過平常 Baseline 的額外 Capacity。
例如:
Normal:
100 RPS
Temporary burst:
500 RPS
Baseline(基準值 / 基本容量)
正常情況下預期或保證的基本 Level。
Users
↓
API Gateway
↓
Identity / SSO Layer
↓
Tenant Context Resolver
↓
RBAC + Entitlement + Quota
↓
┌────────────────┴────────────────┐
↓ ↓
Control Plane Data Plane
↓ ↓
Organization Service AI API
Subscription Service RAG Service
Entitlement Service Agent Service
Tenant Provisioning Agent Workers
SSO / SCIM Config Model Gateway
Billing Config Tool Gateway
↓ ↓
Control Database Tenant-Aware Data Stores
↓
┌─────────────┼──────────────┐
↓ ↓ ↓
PostgreSQL Vector Store Object Storage
↓ ↓ ↓
tenant_id tenant_id tenant_id
Data Plane
↓
Usage Events
↓
Usage Queue
↓
Metering Service
↓
Usage / Cost Database
↓
Billing Service
↓
Invoice
Company IdP
↓
SAML SSO
↓
AI SaaS
↓
User Session
Company Identity Directory
↓
SCIM
↓
Create / Update / Disable Users
記住:
SAML / SSO
→ Login
SCIM
→ User lifecycle
Tenant Data
↓
DEK
↓
Encrypted Data
DEK
↓ encrypted by
KEK / KMS
Enterprise Option:
BYOK
讓 Customer 對 Key Management 有更多 Control。
真正好的 SaaS Isolation 不是只有:
WHERE tenant_id = ?
而是很多 Layers:
Authentication
↓
Tenant Context
↓
RBAC
↓
Entitlement
↓
Database tenant filter
↓
Vector namespace/filter
↓
Object storage namespace
↓
Cache key namespace
↓
Credential isolation
↓
Usage attribution
↓
Audit
Defense in Depth 之前 Security 已經提過,所以直接套用:
不依賴單一 Tenant Isolation Check。
例如:
Application accidentally forgets tenant filter
如果 Database / Storage 還有另一層 Isolation,可以降低 Blast Radius。
錯誤:
Tenant A asks question
↓
Vector Search
↓
No tenant filter
↓
Returns Tenant B document
這是嚴重 Security Incident。
防護:
Tenant-aware namespace
Metadata filter
ACL filter
Integration tests
Security tests
Audit
錯誤:
cache key = document:123
Tenant A:
document 123
Tenant B:
document 123
可能 Collision。
更合理:
tenant_A:document:123
tenant_B:document:123
錯誤:
Tenant A Agent
↓
Tool Gateway
↓
loads Tenant B Gmail token
結果可能造成:
Cross-tenant data access
Credential lookup 必須:
tenant_id
+
user_id
+
tool
一起驗證。
Tenant A
→ 1M Agent Tasks
↓
Shared Workers saturated
↓
Tenant B latency explodes
解法:
Quota
Concurrency Limit
Fair Scheduling
Priority
Per-Tenant Queue
Dedicated Tier
Autoscaling
Task completes
↓
Usage Event emitted
↓
Consumer processes
↓
Consumer crashes before ACK
↓
Message delivered again
如果沒有 Idempotency:
Customer charged twice